package com.example.test.dialogfactory;

import android.Manifest.permission;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.appcompat.app.AppCompatActivity;
import androidx.documentfile.provider.DocumentFile;
import easier.app.x.CommonCode;
import easier.app.x.result.Permission;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;
import java.io.File;
import java.net.URLEncoder;

public class MainActivity103 extends AppCompatActivity {

    private static final String TAG = "MainActivity103";
    private Button pick;

    public static void start( Context context ) {

        Intent starter = new Intent( context, MainActivity103.class );
        context.startActivity( starter );
    }

    @Override
    protected void onCreate( Bundle savedInstanceState ) {

        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main103 );
        initView();
    }

    private void initView() {

        pick = (Button) findViewById( R.id.pick );
        pick.setOnClickListener( new OnClickListener() {
            @Override
            public void onClick( View v ) {

                Observable.create( new ObservableOnSubscribe< Boolean >() {
                        @Override
                        public void subscribe( @NonNull ObservableEmitter< Boolean > emitter ) throws Throwable {

                            Permission.registerForPermissionResult( getSupportFragmentManager(), permission.WRITE_EXTERNAL_STORAGE,
                                new ActivityResultCallback< Boolean >() {
                                    @Override
                                    public void onActivityResult( Boolean result ) {

                                        if ( result ) {
                                            emitter.onNext( Boolean.TRUE );
                                            emitter.onComplete();
                                        } else {
                                            emitter.onError( new IllegalStateException( "没有权限" ) );
                                        }
                                    }
                                } );
                        }
                    } ).flatMap( new Function< Boolean, ObservableSource< Uri > >() {
                        @Override
                        public ObservableSource< Uri > apply( Boolean aBoolean ) throws Throwable {

                            return Observable.create( new ObservableOnSubscribe< Uri >() {
                                @Override
                                public void subscribe( @NonNull ObservableEmitter< Uri > emitter ) throws Throwable {

                                    Intent intent = new Intent( Intent.ACTION_OPEN_DOCUMENT );
                                    intent.setType( "application/pdf" );
                                    intent.setFlags(
                                        Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION );
                                    intent.addCategory( Intent.CATEGORY_OPENABLE );
                                    CommonCode.registerForActivityResult( getSupportFragmentManager(), intent,
                                        new ActivityResultCallback< ActivityResult >() {
                                            @Override
                                            public void onActivityResult( ActivityResult result ) {

                                                Intent resultData = result.getData();
                                                Log.i( TAG, "onActivityResult: " + resultData );
                                                if ( resultData != null && resultData.getData() != null ) {
                                                    Uri data = resultData.getData();
                                                    emitter.onNext( data );
                                                    emitter.onComplete();

                                                } else {
                                                    emitter.onError( new IllegalStateException( "获取失败" ) );
                                                }
                                            }
                                        } );
                                }
                            } );
                        }
                    } )
                    .observeOn( Schedulers.io() )
                    .doOnNext( new Consumer< Uri >() {
                        @Override
                        public void accept( Uri uri ) throws Throwable {

                            DocumentFile documentFile = DocumentFile.fromSingleUri( v.getContext(), uri );
                            if ( documentFile == null ) {
                                Log.i( TAG, "accept: " + "获取文件名字失败" );
                            } else {
                                Log.i( TAG, "accept: " + documentFile.getName() );
                                Log.i( TAG, "accept: " + URLEncoder.encode( documentFile.getName(), "UTF-8" ) );
                            }

                            File file = CommonCode.copyFromUri( v.getContext(), uri, "test", ".pdf" );
                            Log.i( TAG, "onActivityResult: " + file + " " );
                            if ( file != null ) {
                                Log.i( TAG,
                                    "onActivityResult: " + file.exists() + " " + file.getPath() + " "
                                        + file.length() / 1024 / 1024 );
                            }
                        }
                    } )
                    .observeOn( AndroidSchedulers.mainThread() )
                    .subscribe( new Observer< Object >() {
                        @Override
                        public void onSubscribe( @NonNull Disposable d ) {

                        }

                        @Override
                        public void onNext( @NonNull Object o ) {

                        }

                        @Override
                        public void onError( @NonNull Throwable e ) {

                            e.printStackTrace();
                        }

                        @Override
                        public void onComplete() {

                        }
                    } );
            }
        } );
    }
}